package com.lier.gulimall.product.handler;

import com.lier.common.utils.R;
import com.lier.common.valid.ExceptionTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liyd
 * @description 商品服务全局异常处理
 * @date 2025/6/10 17:58
 */
@Slf4j
@RestControllerAdvice("com.lier.gulimall.product.controller")
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     * @param exception controller参数校验异常对象
     * @return 异常json对象
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException exception) {
        Map<String, String> errorMap = new HashMap<>();
        BindingResult bindingResult = exception.getBindingResult();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        return R.error(ExceptionTypeEnum.VALIDATE_EXCEPTION.getCode(),
                ExceptionTypeEnum.VALIDATE_EXCEPTION.getMessage())
                .put("data", errorMap);
    }
}
